package com.idol.controller;

import com.idol.annotation.Autowired;
import com.idol.pojo.Result;
import com.idol.service.AccountService;
import com.idol.service.impl.AccountServiceImpl;
import com.idol.util.JsonUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className AccountServlet
 * @description
 * @date 2020/10/13 13:25
 **/
@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class AccountServlet extends MyHttpServlet {
    @Autowired
    private AccountService accountService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {

            // 2. 调用service层方法
            accountService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtil.object2Json(result));
    }

}
